package com.hq.fxh.No1_Infromation.Video.Activity;

import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.NotificationCompat;
import android.util.Log;

import com.google.gson.GsonBuilder;

import com.hq.fxh.HttpApi.UserServiceImpl;
import com.hq.fxh.Intefers.NetworkSubscriber;
import com.hq.fxh.Modle.GetVideoListModle;
import com.hq.fxh.Modle.UploadImgRes;
import com.hq.fxh.No3_TuiGuang.MyMoBan.Activity.item.ToastUtils;
import com.hq.fxh.No3_TuiGuang.MyMoBan.Model.CommonRes;
import com.hq.fxh.Utils.LogUtils;
import com.hq.fxh.Utils.SharedPreferenceUtils;
import com.hq.fxh.imageLoader.video.VideoItem;
import com.hq.fxh.imageLoader.video.VideoPicker;
import com.tencent.upload.Const;
import com.tencent.upload.UploadManager;
import com.tencent.upload.task.ITask;
import com.tencent.upload.task.IUploadTaskListener;
import com.tencent.upload.task.VideoAttr;
import com.tencent.upload.task.data.FileInfo;
import com.tencent.upload.task.impl.VideoUploadTask;
import com.tencent.upload.utils.Base64;


import java.io.ByteArrayOutputStream;
import java.util.Date;

import static com.tencent.upload.common.Global.context;


/**
 * @author 小谢
 * @ClassName UpLoadVideoProgressUtils
 * @Description :
 * @Created 2017/4/6 0006
 */
public class UpLoadVideoProgressUtils {
    private static VideoUploadTask videoUploadTask = null;
    private static VideoPicker videoPicker;
    private static Handler mMainHandler;
    private static UploadManager mFileUploadManager = null;
    static NotificationCompat.Builder builder;
    static NotificationManager manager;

    public static void upLoadCoverImg(final Context context, final String title, Bitmap bitmap, NotificationCompat.Builder builder1,
                                      NotificationManager manager1) {
        builder = builder1;
        manager = manager1;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] b = baos.toByteArray();
        String videoCoverImg = Base64.encodeToString(b, Base64.DEFAULT);
        UserServiceImpl.uploadImg("videoCoverImg", videoCoverImg, String.valueOf(6), new NetworkSubscriber<UploadImgRes>() {
            @Override
            public int onSuccess(UploadImgRes data) {
                super.onSuccess(data);
                if (data != null && data.getCode() == 0) {
                    String videoCoverImgurl = data.getData().getUrl();
                    upLoadVideo(context, title, true, videoCoverImgurl);
                } else {
                    ToastUtils.show(context, data.getMsg());
                }
                return 0;
            }
        });
    }

    private static void upLoadVideo(final Context context, final String title, boolean to_over_write, String videoCoverurl) {
        videoPicker = VideoPicker.getInstance();
        VideoItem videoItem = videoPicker.getSelectedVideos().get(0);
        String mFilePath = videoItem.path;
        mMainHandler = new Handler(Looper.getMainLooper());
        if (mFilePath == null) {
            ToastUtils.show(context, "请选择视频");
            return;
        }
        String appid = "10012792";
        String bucket = "video";
        String persistenceId = "videPersistenceId";
        mFileUploadManager = new UploadManager(context, appid, Const.FileType.Video, persistenceId);

        int uid = SharedPreferenceUtils.getMemberId(context);
        VideoAttr videoAttr = new VideoAttr();
        videoAttr.isCheck = false;
        String timestamp = new Date().getTime() + "" + (int) (Math.random() * 1000);
        videoAttr.title = title;
        long timeLong = videoItem.timeLong;
        videoAttr.timeLen = timeLong;
        videoAttr.desc = "";
        String nameend = mFilePath.substring(mFilePath.lastIndexOf("."));//后缀

        UpLoadVideoRes upLoadVideoRes = new UpLoadVideoRes(uid, title, videoCoverurl, videoPicker.timeParse(videoItem.timeLong));
        final String videoUploadInfoJson = new GsonBuilder().create().toJson(upLoadVideoRes, UpLoadVideoRes.class);
        Log.e("eeeeInfoJson:", "  " + videoUploadInfoJson);

        Log.e("eeeeeeeeeeee", "bucket:" + bucket + "   mfilePath:" + mFilePath + "    path: 是 " + "/Android/" + timestamp + nameend + "    videoAttr: " + videoAttr + "    to_Over_write:" + to_over_write);
        //1507700406988683.mp4
        videoUploadTask = new VideoUploadTask(bucket, mFilePath, "/Android/" + timestamp + nameend, "", videoAttr, to_over_write, new IUploadTaskListener() {
            @Override
            public void onUploadSucceed(final FileInfo result) {
              /*  EventBus.getDefault().post(new RefreshPostCountEvent());
                EventBus.getDefault().post(new UploadProgressEvent(title, 100, 1));*/
                LogUtils.e("视频上传成功");
            }

            @Override
            public void onUploadStateChange(ITask.TaskState state) {
/*Error:Cannot change artifacts of configuration ':app:default' after it has been included in dependency resolution.*/
            }

            @Override
            public void onUploadProgress(final long totalSize, final long sendSize) {
                int p = (int) ((sendSize * 100) / (totalSize * 1.0f));
             /*   EventBus.getDefault().post(new UploadProgressEvent(title, p, 1));*/

                builder.setProgress(100, (int) p * 100, false);
                manager.notify(0x3, builder.build());
                //下载进度提示
                builder.setContentText("上传" + p + "%");
                LogUtils.e("视频上传进度" + title + "   " + p + "   " + 1);

            }

            @Override
            public void onUploadFailed(final int errorCode, final String errorMsg) {
                LogUtils.e("视频上传失败" + errorCode + "  " + errorMsg);
            }
        });

        UserServiceImpl.getVideoUploadSign(new NetworkSubscriber<CommonRes>() {
            @Override
            public int onSuccess(CommonRes data) {
                super.onSuccess(data);
                if (data.getCode() == 0) {
                    String sign = data.getData().toString();
                    videoUploadTask.authIsEmpty();
                    videoUploadTask.setAuth(sign);
                    Log.e("eeeesign:", "  " + sign);
                    videoUploadTask.setBusiMsg(videoUploadInfoJson);
                    mFileUploadManager.upload(videoUploadTask); //开始上传*/
                } else {
                    ToastUtils.show(context, data.getMsg());
                }
                return 0;
            }
        });

    }


}
